//
//  UserAcoount.swift
//  Sina
//
//  Created by 邹志华 on 15/11/8.
//  Copyright © 2015年 zzh. All rights reserved.
//

import UIKit

class UserAcoount: NSObject {

    
    ///用于调用access_token,接口获取授权后的access token
    var access_token:String?
    
    ///access_token 的生命周期,单位是秒数
    var expires_in:NSTimeInterval = 0{
        didSet{
            expires_date = NSDate(timeIntervalSinceNow:expires_in)
            print("expires_date:\(expires_date)")
            
        }
    }
    
    ///当前授权用户的UID
    var uid:String?
    
       var  expires_date:NSDate?
    
    //KVC字典转模型
    init(dict:[String:AnyObject]){
        
        super.init()
        ///将字典里面的没一个key的值赋值给对应的模型属性
        setValuesForKeysWithDictionary(dict)
    }
    
    //当字典里面的key在模型里面没有对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
//        print("forUndefinedKey:\(key)")
    }
    override var description:String{
        return "access_token:\(access_token),expires_in:\(expires_in),uid:\(uid):expires_date:\(expires_date)"
    }
    
  static  let accontPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory    , NSSearchPathDomainMask.UserDomainMask,true).last! + "/Account.plist"
    //MARK: - 保存对象
    func saveAccount(){
        
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAcoount.accontPath)
    }
    
    class func loadAccount()->UserAcoount? {
     
    let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accontPath) as?UserAcoount
        return account
    }
    
    
    //MARK: - 归档和解党
    func encodeWithCoder(aCoder:NSCoder){
    
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
          aCoder.encodeObject(expires_date, forKey: "expires_date")
//expires_date
    }
    
   required init?(coder aDecoder:NSCoder){
    access_token = aDecoder.decodeObjectForKey("access_token")as? String
    expires_in = aDecoder.decodeDoubleForKey("expires_in")
       uid = aDecoder.decodeObjectForKey("uid")as? String

    expires_date = aDecoder.decodeObjectForKey("expires_date")as?NSDate
    
    
    }
    
}
